import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import i18n from '@/lang'
import { getToken } from '@/utils/cookies'
import { Base64 } from 'js-base64'
import settings from '@/settings'

const encodeToken = () => {
  const token = getToken()
  const base64 = Base64.encode(`${token}:`)
  return `Basic ${base64}`
}

const denyRequest = (config) => {
  if (settings.isDemo === true) {
    const isDeny = !(config.url.includes('/get') ||
                    config.url.includes('/search') ||
                    config.url.includes('/find') ||
                    config.url.includes('/login') ||
                    config.url.includes('/logout') ||
                    config.url.includes('/query') ||
                    config.url.includes('/upload') ||
                    config.url.includes('/auth'))
    if (isDeny) {
      throw new Error('Demo 环境，禁止修改操作。')
    }
  }
}
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    denyRequest(config)
    if (store.getters.language) {
      config.headers.language = store.getters.language
    }
    if (store.getters.token) {
      config.headers.Authorization = encodeToken()
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.error) {
      // 10006 : 需要携带token值, 10007 : token已过期
      const errCode = String(res.error.errorCode)
      if (errCode === '10006' || errCode === '10007') {
        const lang = i18n.getLocaleMessage(store.getters.language || 'zh')['common']['msgBox']['tokenExpired']
        MessageBox.confirm(lang.msg, lang.title, {
          confirmButtonText: lang.ok,
          cancelButtonText: lang.cancel,
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
        return res
      } else {
        Message({
          message: res.error.message || res.error.err?.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
      }
      return Promise.reject(new Error(res.error.message || res.error.err?.message || 'Error'))
    } else {
      const newToken = response.headers.get('new_token')
      if (newToken) {
        store.dispatch('user/changeToken', newToken)
      }
      if (res.success) {
        Message({
          message: res.success.message,
          type: 'success',
          duration: 3 * 1000
        })
      }
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
